package com.itcast.tanhuarecommend.msg;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itcast.tanhuarecommend.domain.RecommendVideo;
import com.itcast.tanhuarecommend.domain.Video;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.invoke.SwitchPoint;

/**
 * @PachageName: com.itcast.tanhuarecommend.msg
 * @ClassName:
 * @Description: TODO
 * @Author: Hushi
 * @DateTime: 2021/2/2519:41
 * @Version 1.0
 */
@Component
@RocketMQMessageListener(topic = "tanhua-video",
        consumerGroup = "tanhua-video-consumer")
@Slf4j
public class VideoMsgConsumer implements RocketMQListener<String> {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void onMessage(String msg) {
        try {
            JsonNode jsonNode = MAPPER.readTree(msg);
            long userId = jsonNode.get("userId").asLong();
            long vid = jsonNode.get("vid").asLong();
            int type = jsonNode.get("type").asInt();
            //1-发动态，2-点赞， 3-取消点赞，4-评论
            RecommendVideo recommendVideo = new RecommendVideo();
            recommendVideo.setId(ObjectId.get());
            recommendVideo.setDate(System.currentTimeMillis());
            recommendVideo.setUserId(userId);
            recommendVideo.setVideoId(vid);

            switch (type){
                case 1:
                    recommendVideo.setScore(2d);
                    break;
                case 2:
                    recommendVideo.setScore(5d);
                    break;
                case 3:
                    recommendVideo.setScore(-5d);
                    break;
                case 4:
                    recommendVideo.setScore(10d);
                    break;
                default:
                    recommendVideo.setScore(0d);
                    break;
            }

            String collectionName = "recommend_video_" + new DateTime().toString("yyyyMMdd");
            this.mongoTemplate.save(recommendVideo,collectionName);

        } catch (IOException exception) {
            exception.printStackTrace();
            log.error("处理小视频消息失败~ msg=" + msg,exception);
        }

    }
}
